package com.chenxin.framework.aspectj;

import com.alibaba.fastjson2.JSON;
import com.chenxin.common.annotation.WmsLogs;
import com.chenxin.common.core.domain.ProcResult;
import com.chenxin.common.core.domain.entity.SysUser;
import com.chenxin.common.core.domain.model.LoginUser;
import com.chenxin.common.core.text.Convert;
import com.chenxin.common.exception.wms.WmsException;
import com.chenxin.common.utils.ExceptionUtil;
import com.chenxin.common.utils.SecurityUtils;
import com.chenxin.common.utils.ServletUtils;
import com.chenxin.common.utils.StringUtils;
import com.chenxin.framework.manager.AsyncManager;
import com.chenxin.framework.manager.factory.AsyncFactory;
import com.chenxin.system.domain.WmsLog;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.NamedThreadLocal;
import org.springframework.stereotype.Component;

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Map;

/**
 * 业务日志记录处理
 *
 * @author gry
 */
@Aspect
@Component
public class WmsLogsAspect {
    private static final Logger log = LoggerFactory.getLogger(LogAspect.class);
    /**
     * 计算操作消耗时间（使用双端队列管理）
     */
    private static final ThreadLocal<Deque<Long>> TIME_DEQUE = new NamedThreadLocal<>("WMS Time Stack");

    /**
     * 处理请求前执行
     */
    @Before(value = "@annotation(controllerLog)")
    public void doBefore(JoinPoint joinPoint, WmsLogs controllerLog) {
        Deque<Long> deque = TIME_DEQUE.get();
        if (deque == null) {
            deque = new ArrayDeque<>(4); // 初始容量设为4，减少扩容
            TIME_DEQUE.set(deque);
        }
        deque.push(System.currentTimeMillis());
    }

    /**
     * 处理完请求后执行
     *
     * @param joinPoint 切点
     */
    @AfterReturning(pointcut = "@annotation(controllerLog)", returning = "jsonResult")
    public void doAfterReturning(JoinPoint joinPoint, WmsLogs controllerLog, Object jsonResult) {
        handleLog(joinPoint, controllerLog, null, jsonResult);
    }

    /**
     * 拦截异常操作
     *
     * @param joinPoint 切点
     * @param e         异常
     */
    @AfterThrowing(value = "@annotation(controllerLog)", throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint, WmsLogs controllerLog, WmsException e) {
        handleLog(joinPoint, controllerLog, e, null);
    }


    protected void handleLog(final JoinPoint joinPoint, WmsLogs controllerLog, final WmsException e, Object jsonResult) {
        try {
            // 获取当前的用户
            LoginUser loginUser = SecurityUtils.getLoginUser();
            // *========WMS作业日志=========*//
            WmsLog wmsLog = new WmsLog();
            if (loginUser != null) {
                wmsLog.setCreator(loginUser.getUserId());
            }
            // 如果业务异常
            if (e != null) {
                wmsLog.setLogCode(e.getCode());
                wmsLog.setLogMsg(StringUtils.substring(Convert.toStr(e.getMessage(), ExceptionUtil.getExceptionMessage(e)), 0, 2000));
            }
            // 设置方法名称
            Object target = joinPoint.getTarget();
            String className = "unknown";
            if (target != null) {
                className = target.getClass().getSimpleName();
            }
            String methodName = joinPoint.getSignature().getName();
            wmsLog.setLogProc(className + "." + methodName);

            // 处理设置注解上的参数
            getControllerMethodDescription(joinPoint, controllerLog, wmsLog, jsonResult);
            // 设置消耗时间
            calculateCostTime(wmsLog);
            // 保存数据库
            AsyncManager.me().execute(AsyncFactory.recordWmsLog(wmsLog));
        } catch (Exception exp) {
            // 记录本地异常日志
            log.error("异常信息:{}", exp.getMessage());
            exp.printStackTrace();
        }
    }

    /**
     * 获取注解中对方法的描述信息 用于Controller层注解
     *
     * @param wmsLogs 日志
     * @param wmsLog  操作日志
     * @throws Exception
     */
    public void getControllerMethodDescription(JoinPoint joinPoint, WmsLogs wmsLogs, WmsLog wmsLog, Object jsonResult) throws Exception {
        // 方法名称
        wmsLog.setLogName(wmsLogs.name());
        // 获取参数信息保存到数据库中
        setRequestValue(joinPoint, wmsLog);
        if (StringUtils.isNotNull(jsonResult) && jsonResult instanceof ProcResult) {
            ProcResult result = (ProcResult) jsonResult;
            wmsLog.setLogCode(result.getCode());
            wmsLog.setLogMsg(result.getMessage());
        }
    }

    /**
     * 获取请求的参数，放到log中
     *
     * @throws Exception 异常
     */
    private void setRequestValue(JoinPoint joinPoint, WmsLog wmsLog) throws Exception {
        Map<?, ?> paramsMap = ServletUtils.getParamMap(ServletUtils.getRequest());
        if (StringUtils.isEmpty(paramsMap)) {
            String params = argsArrayToString(joinPoint.getArgs());
            wmsLog.setLogParam(StringUtils.substring(params, 0, 2000));
        } else {
            wmsLog.setLogParam(StringUtils.substring(JSON.toJSONString(paramsMap), 0, 2000));
        }
    }

    /**
     * 参数拼装
     */
    private String argsArrayToString(Object[] paramsArray) {
        String params = "";
        if (paramsArray != null && paramsArray.length > 0) {
            for (Object o : paramsArray) {
                if (StringUtils.isNotNull(o)) {
                    try {
                        String jsonObj = JSON.toJSONString(o);
                        params += jsonObj + " ";
                    } catch (Exception e) {
                    }
                }
            }
        }
        return params.trim();
    }

    private void calculateCostTime(WmsLog wmsLog) {
        Deque<Long> deque = TIME_DEQUE.get();
        if (deque != null && !deque.isEmpty()) {
            wmsLog.setCostTime(System.currentTimeMillis() - deque.pop());
        }
    }
}
